package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("1003")
public class VipStrategy implements ItemTypeStrategy {

    @Autowired
    private UserInfoMapper userInfoMapper;


    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;


    @Autowired
    private UserVipServiceMapper userVipServiceMapper;


    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {

        //  这个是vip 1003
        //  vip user_vip_service
        //  需要获取用户的身份信息！
        try {
            UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
            //  还需要获取到用户购买有效期！
            Long serviceId = userPaidRecordVo.getItemIdList().get(0);
            VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(serviceId);
            //  创建对象：
            UserVipService userVipService = new UserVipService();
            userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
            userVipService.setUserId(userPaidRecordVo.getUserId());
            userVipService.setStartTime(new Date());
            //  创建对象
            LocalDateTime localDateTime = new LocalDateTime(new Date());
            //  判断续期情况：当前用户属于VIP 并且 过期时间在系统时间之后！
            if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(new Date())) {
                //  在过期时间基础上+购买时间;
                Date vipExpireTime = userInfo.getVipExpireTime();
                //  创建localDateTime
                localDateTime = new LocalDateTime(vipExpireTime);
            }
            //  获取过期时间
            Date vipExpireTime = localDateTime.plusMonths(vipServiceConfig.getServiceMonth()).toDate();
            //  设置过期时间
            userVipService.setExpireTime(vipExpireTime);
            //  保存数据
            userVipServiceMapper.insert(userVipService);

            //int i = 1/0;
            //  修改用户的vip状态
            userInfo.setIsVip(1);
            userInfo.setVipExpireTime(vipExpireTime);
            //  更新数据:
            userInfoMapper.updateById(userInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
